package com.neusoft.demo.controller;

import com.neusoft.demo.entity.User;
import com.neusoft.demo.pojo.dto.UserDto;
import com.neusoft.demo.repository.UserRepository;
import com.neusoft.demo.util.RestResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Optional;

/**
 * @author BBQ
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserRepository userRepository;

    /**
     * 获取列表
     * @return
     */
    @GetMapping("list")
    @ResponseBody
    public RestResponse list() {
        return RestResponse.success().setData(userRepository.findAll());
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ResponseBody
    public RestResponse user(@PathVariable Long id) {
        Optional<User> optUser = userRepository.findById(id);
        if (optUser.isPresent()) {
            return RestResponse.success().setData(optUser.get());
        }
        return RestResponse.failure().setMessage("记录不存在");
    }

    /**
     * 保存
     * @param dto
     * @return
     */
    @PostMapping
    public RestResponse save(@Valid UserDto dto) {
        User user = new User();
        BeanUtils.copyProperties(dto, user);
        user = userRepository.save(user);
        return RestResponse.success().setData(user);
    }

    public Page<User> page() {
        return userRepository.findAll(PageRequest.of(1, 10));
    }

}
